package com.itgacl.magic4j.libcommon.component.ws.cluster.redis;

import com.itgacl.magic4j.libcommon.component.ws.cluster.Constants;
import com.itgacl.magic4j.libcommon.component.ws.cluster.listener.WebsocketMsgListener;
import com.itgacl.magic4j.libcommon.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.util.concurrent.Executors;

/**
 * Redis订阅消息配置
 */
@ConditionalOnProperty(prefix = "ws", value = "enable", havingValue = "true")
@Slf4j
@Configuration
public class RedisSubscribeTopicConfig {

    /**
     * 消息监听器
     */
    @Bean
    MessageListenerAdapter messageListenerAdapter(WebsocketMsgListener websocketMsgListener, Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer){
        //消息接收者以及对应的默认处理方法
        MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(websocketMsgListener, "receiveMessage");
        //消息的反序列化方式
        messageListenerAdapter.setSerializer(jackson2JsonRedisSerializer);
        return messageListenerAdapter;
    }

    /**
     * 订阅topic
     * @param redisConnectionFactory
     * @param messageListenerAdapter
     * @return
     */
    @Bean
    RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory,MessageListenerAdapter messageListenerAdapter) {
        final RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        String serverIp = IpUtil.getLocalIP();
        String subscribeTopic = serverIp+ Constants.TOPIC.WEBSOCKET_MSG_NOTIFY;//需要订阅的topic
        //可以添加多个 messageListener
        container.addMessageListener(messageListenerAdapter, new PatternTopic(subscribeTopic));
        container.setTaskExecutor(Executors.newFixedThreadPool(4));
        log.debug("订阅topic:{}",subscribeTopic);
        return container;
    }
}
